Telegram Group & Telegram Channel
🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6561
Create:
Last Update:

🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6561

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

A project of our size needs at least a few hundred million dollars per year to keep going,” Mr. Durov wrote in his public channel on Telegram late last year. “While doing that, we will remain independent and stay true to our values, redefining how a tech company should operate.

Библиотека джависта | Java Spring Maven Hibernate from sg


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA